<?php
/**
 * Created by lzl
 * Date: 2021 2021/11/10
 * Time: 15:54
 */
namespace App\Services\Admin;
use App\Exceptions\RequestException;
use App\Forms\ExpressForms;
use App\Forms\OrderForms;
use App\Models\Order;
use App\Services\BaseServices as Base;

class OrderServices extends Base
{

    /**
     * 订单发货
     * //TODO 这部分有时间可以放在事件监听里
     * @param $validated
     * @return bool
     * @throws RequestException
     * @throws \Throwable
     */
    public function deliver($validated)
    {
        $orderForms = new OrderForms();

        $order = $orderForms->getOrderDetail($validated['id']);

        \DB::beginTransaction();

        try {

            if ($order->status != Order::DELIVER) {
                throw new RequestException('订单状态异常');
            }

            $validated['order_id'] = $validated['id'];

            unset($validated['id']);


            //物流数据
            $express = (new ExpressForms())->createOrderExpress($validated);

            //todo 抓取物流信息


            //更新订单状态
            $orderForms->updateOrder($validated['order_id'], [
                'status'           => Order::RECEIVING,
                'delivery_time'    => date('Y-m-d H:i:s'),
                'order_express_id' => $express->id,
            ]);

            \DB::commit();

            return true;

        } catch (\Exception $e) {
            \DB::rollBack();
            throw new RequestException($e->getMessage());
        }


    }
}